package edu.ptu.shortlink.admin.toolkit;

import com.alibaba.excel.EasyExcel;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @BelongsProject: shortlink
 * @BelongsPackage: edu.ptu.shortlink.admin.toolkit
 * @Author: HYJ
 * @CreateTime: 2025-05-12  19:42
 * @Description: 封装EasyExcelWeb工具类
 * @Version: 1.0
 */
public class EasyExcelWebUtil {
    /**
     * 向浏览器输出Excel文件
     *
     * @param response 响应
     * @param fileName 文件名称
     * @param clazz    导出数据类型
     * @param data     导出数据
     */
    @SneakyThrows
    public static void write(HttpServletResponse response, String fileName, Class<?> clazz, List<?> data) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        // 这里URLEncoder.encode可以防止中文乱码 当然和EasyExcel没有关系
        fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz)
                .sheet("Sheet")
                .doWrite(data);
    }
}
